
var gulp = require('gulp');
// gulp-xxx 高质量插件库
var less = require('gulp-less');
var yscss = require('gulp-clean-css');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var bs = require('browser-sync').create();
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var imagemin = require('gulp-imagemin');//图片压缩
var pngcrush = require('imagemin-pngcrush');

// less转换css的功能
// 获取文件 通过一些插件进行处理 输出为css文件
gulp.task('lesys', function(){
    // 把less文件编译css
    gulp.src('ceshi/less/*.less')       // 获取文件
        .pipe( less() )                 // 处理文件 
        .pipe( autoprefixer({
            browsers: ['last 2 versions']
        }) )                           // 加css前缀
        .pipe( gulp.dest('zsbb/css') )  // 输出
        .pipe( yscss() )
        .pipe( rename({suffix: '.min'}) )
        .pipe( gulp.dest('zsbb/css') );
})
//压缩js
gulp.task('ysjs',function(){
    gulp.src('ceshi/js/*.js')
    .pipe(uglify())   
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('zsbb/js'));
})

// 压缩图片
gulp.task('ysimg', function() {
    return gulp.src('ceshi/images/*.{png,jpg,gif,ico}')
      .pipe(imagemin({
          progressive: true,
          svgoPlugins: [{removeViewBox: false}],
          use: [pngcrush()]
      }))
      .pipe(gulp.dest('zsbb/images/'))
});

//压缩html
gulp.task('yshtml', function () {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    gulp.src('ceshi/*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('zsbb/'));

    gulp.src('ceshi/html/*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('zsbb/html/'));    
});

//
gulp.task('refresh', function(){
    bs.reload();
})

// 监听
gulp.task('zidong', function(){

    gulp.watch('ceshi/less/*.less', ['lesys']);

    gulp.watch('ceshi/js/*.js', ['ysjs']);
    
    gulp.watch('ceshi/html/*.html', ['yshtml']);
    gulp.watch('ceshi/*.html', ['yshtml']);

    gulp.watch('ceshi/images/*.{png,jpg,gif,ico}', ['ysimg']);

    gulp.watch('zsbb/*.html', ['refresh']);

})

// 启动本地服务
// browserSync 同步测试工具 释放你的f5
gulp.task('serve', function(){

    bs.init({
        server: {
            baseDir: 'ceshi'
        },
        startPath: "index.html"
    })

})

gulp.task('default', function(){
    gulp.run('serve', 'zidong');
})

